package com.cfushn.ddd.catchlog;

import com.cfushn.ddd.application.dto.CodeEnum;
import com.cfushn.ddd.application.dto.res.ResDTO;
import com.cfushn.ddd.exception.BizException;
import com.cfushn.ddd.exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * GlobalExceptionHandler
 *
 * @author CFuShn 2022/4/2 13:45
 */
@RestControllerAdvice
@Slf4j
@ConditionalOnMissingBean(GlobalExceptionHandler.class)
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResDTO<String> bizException(BizException e) {
        log.warn("BIZ EXCEPTION : {}", e.getMessage());
        // 对于BizException,仅在Debug的时候打印堆栈
        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        }
        return ResDTO.failed(null, e.getErrCode(), e.getMessage());
    }

    @ExceptionHandler(SysException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResDTO<String> sysException(SysException e) {
        // 对于SysException，总是打印堆栈
        log.error("SYS EXCEPTION: {}", e.getMessage(), e);
        return ResDTO.failed(null, e.getErrCode(), e.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResDTO<String> error(Exception e) {
        // 未知错误, 总是打印堆栈
        log.error("UNKNOWN EXCEPTION: {}", e.getMessage(), e);
        return ResDTO.failed(e.toString(), CodeEnum.ERROR.getCode(), e.getMessage());
    }

}
